# -*-coding:utf-8-*-

import time, os, socket, sys, json, re, websocket, threading, struct, binascii
import logConfig as log
import httplib, urllib, urllib2, cookielib
from base import *
from interfaceFunc import *
from threadCenter import *

# Json数据加载
def preHandleMsg(msg):
    data = msg.replace('!','').replace('$','')
    try:
        data = "".join([ data.strip().rsplit("}" , 1)[0] ,  "}"] )
        data = json.loads(data)
    except(ValueError), e:
        log.error("Error is occur in preHandleMsg, The error is Json format error, detail: "+str(e)+"\nThe data is: "+data)
    else:
        return data

# 程序的自我销毁
def selfDestructive():
    time.sleep(0.5)
    pid = str(os.getpid())
    os.system("taskkill /f /PID " + pid + " >> " + log.log_path)

# 预留的心跳函数接口
def heartbeat(ws, cmpid, uid, token):
    while True:
        ws.wsTcpSend(assemblyTCPData(2, 1, 0, getHeartBeatMsg(cmpid, uid, token)),0)
        time.sleep(10)

# rtp心跳函数
def heartbeatRtp(udpSocket):
    while True:
        udpSocket.send()
        time.sleep(10)

# 获取当前设备的网络状态
def netstatCheck(datacenter):
    while True:
        try:
            command = socket.gethostbyname("baidu.com")
        except Exception, e:
            datacenter.netstatus = 0
        else:
            datacenter.netstatus = 1
        time.sleep(2)

# 组装rtp数据包
def getRtpPackage(sid, cid, uid):
    mid = getTimestamp()
    PayLoadType = 50
    SequenceNumber = 33
    Timestamp = int(str(mid)[9:])
    SSRC = int(sid)
    hex_header = byteCheck(hex(PayLoadType), 1)+byteCheck(hex(SequenceNumber), 2)+byteCheck(hex(Timestamp), 4)+byteCheck(hex(SSRC), 4)
    rtpHeader = hex_header.replace("0x","")
    rtpContent = byteCheck(hex(sid), 4) + byteCheck(hex(cid), 4) + byteCheck(hex(uid), 4) + byteCheck(hex(Timestamp), 4)    
    return rtpHeader+rtpContent

    #rtpHeader = "320021000014a00000168A" #51
    #data = struct.pack("iiii", sid, cid, uid, int(str(mid)[7:]))
    #rtpdata = rtpHeader + binascii.hexlify(data)

# Http请求中Cookie的设置
def make_cookie(name, value, server):
    return cookielib.Cookie(
        version=0,
        name=name,
        value=value,
        port=None,
        port_specified=False,
        domain=server,
        domain_specified=True,
        domain_initial_dot=False,
        path="/",
        path_specified=True,
        secure=False,
        expires=None,
        discard=False,
        comment=None,
        comment_url=None,
        rest=None
    )

# 对讲机数据交互方法封装,application
def fnHttpPost_app(ip, port, reqAddr, data):
    timeout = 3000
    httpClient = None

    try:
        params = urllib.urlencode(data)
        headers = {"Content-type": "application/x-www-form-urlencoded; charset=UTF-8", "Accept": "application/json; charset=UTF-8"}

        httpClient = httplib.HTTPConnection(ip, port, timeout=timeout)
        httpClient.request("POST", reqAddr, params, headers)
        log.info("Http Send:  " + str(data))
        log.TestLog(("Http Send:==========>" + "\n\tdata:\t" + str(data)+ "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))

        response = httpClient.getresponse()
        if (response.status == 200):
            dataAck = response.read()
            log.info("Http Recv:  " + dataAck.decode("utf-8"))
            log.TestLog(("Http  Ack:<==========\n\t" + "data_true:\t" + str(dataAck) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
            return {"status": "success", "content": json.loads(dataAck)}

        else:
            dataAck = str(response.status)+":"+response.reason
            log.info(("Http  Ack:<==========\n\t" + "data_false:\t" + str(dataAck) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
            log.TestLog(("Http  Ack:<==========\n\t" + "data_false:\t" + str(dataAck) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
            return {"status": "fail", "content": dataAck}
    except Exception, e:
        log.info(("Http  Ack:<==========\n\t" + "data_error:\t" + str(e) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
        log.TestLog(("Http  Ack:<==========\n\t" + "data_error:\t" + str(e) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
        return {"status": "error", "content": e}
    finally:
        if httpClient:
            httpClient.close()

# 对讲机数据交互方法封装,text
def fnHttpPost(ip, port, reqAddr, data, lock=None):
    timeout = 300
    httpClient = None

    if lock == None:
        try:
            params = urllib.urlencode(data)
            headers = {"Content-type": "application/x-www-form-urlencoded; charset=UTF-8", "Accept": "text/json; charset=UTF-8"}

            httpClient = httplib.HTTPConnection(ip, port, timeout=timeout)
            httpClient.request("POST", reqAddr, params, headers)
            log.TestLog(("Http Send:==========>" + "\n\tdata:\t" + str(data) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
            log.info("Http Send:  " + str(data))

            response = httpClient.getresponse()
            if (response.status == 200):
                dataAck = response.read()
                log.TestLog(("Http  Ack:<==========\n\t" + "data_true:\t" + str(dataAck) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
                log.info(("Http  Ack:<==========\n\t" + "data_true:\t" + str(dataAck) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
                return {"status": "success", "content": json.loads(dataAck)}
            else:
                dataAck = str(response.status)+":"+response.reason
                log.TestLog(("Http  Ack:<==========\n\t" + "data_false:\t" + str(dataAck) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
                log.info(("Http  Ack:<==========\n\t" + "data_false:\t" + str(dataAck) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
                return {"status": "fail", "content": dataAck}
        except Exception, e:
            log.TestLog(("Http  Ack:<==========\n\t" + "data_error:\t" + str(e) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
            log.info(("Http  Ack:<==========\n\t" + "data_error:\t" + str(e) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
            return {"status": "error", "content": e}
        finally:
            if httpClient:
                httpClient.close()
    else:
        try:
            params = urllib.urlencode(data)
            headers = {"Content-type": "application/x-www-form-urlencoded; charset=UTF-8", "Accept": "text/json; charset=UTF-8"}

            httpClient = httplib.HTTPConnection(ip, port, timeout=timeout)
            httpClient.request("POST", reqAddr, params, headers)
            if lock.acquire():
                log.TestLog(("Http Send:==========>" + "\n\tdata:\t" + str(data) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
                lock.release()
            #log.info("Http Send:  " + str(data))

            response = httpClient.getresponse()
            if (response.status == 200):
                dataAck = response.read()
                if lock.acquire():
                    log.TestLog(("Http  Ack:<==========\n\t" + "data_true:\t" + str(dataAck) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
                    lock.release()
                return {"status": "success", "content": json.loads(dataAck)}
            else:
                dataAck = str(response.status)+":"+response.reason
                if lock.acquire():
                    log.TestLog(("Http  Ack:<==========\n\t" + "data_false:\t" + str(dataAck) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
                    lock.release()
                return {"status": "fail", "content": dataAck}
        except Exception, e:
            if lock.acquire():
                log.TestLog(("Http  Ack:<==========\n\t" + "data_error:\t" + str(e) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
                lock.release()
            return {"status": "error", "content": e}
        finally:
            if httpClient:
                httpClient.close()

def fnHttpPost_onSuccess(dataAck):
    log.info("Http Recv:  " + dataAck.decode("utf-8"))
    log.TestLog(("Http  Ack:<==========\n\t" + "data:\t" + str(dataAck) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
    return {"status": "success", "content": json.loads(dataAck)}

def fnHttpPost_onFail(dataAck):
    log.TestLog(("Http  Ack:<==========\n\t" + "data:\t" + str(dataAck) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
    return {"status": "fail", "content": dataAck}

def fnHttpPost_onError(e):
    log.TestLog(("Http  Ack:<==========\n\t" + "data:\t" + str(e) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
    return {"status": "error", "content": e}

# 封装Http请求
def HttpClientPost(data, ip, port, reqAddr):
    timeout = 30
    httpClient = None

    try:
        params = urllib.urlencode(data)
        headers = {"Content-type": "application/x-www-form-urlencoded; charset=UTF-8", "Accept": "application/json"}

        httpClient = httplib.HTTPConnection(ip, port, timeout=timeout)
        httpClient.request("POST", reqAddr, params, headers)
        log.info("Http Send:  " + str(data))

        response = httpClient.getresponse()

        # 封装函数中需要对请求的反馈状态进行处理：
        #    1.发起请求的代码本身错误，程序会进入except分支>                      输出错误信息 {"status":"fail","content":error}
        #    2.发起请求的代码本身正确，但请求的url或参数有误，未能与服务器建立连接>    输出错误信息 {"status":"fail","content":error}
        #    3.发起请求成功，但请求数据有误，服务器返回对应的错误信息>               检查reponse的status的值不为200 {"status":"fail","content":response.reason}
        #    4.发起请求成功，请求正常返回，服务器返回对应的数据信息>                检查reponse的status的值为200 {"status":"success","content":response.read()}

        if (response.status == 200):
            content = response.read()
            log.info("Http Recv:  " + content.decode("utf-8"))
            return {"status": "success", "content": content.decode("utf-8")}
        else:
            return {"status": "fail", "content": response.reason}

    except Exception, e:
        return {"status": "Error", "content": e}
    finally:
        if httpClient:
            httpClient.close()

# 配合PyUnit测试封装的Http请求
def HttpPost(data, ip, port, reqAddr):
    timeout = 30
    httpClient = None

    try:
        params = urllib.urlencode(data)
        headers = {"Content-type": "application/x-www-form-urlencoded; charset=UTF-8", "Accept": "application/json"}

        httpClient = httplib.HTTPConnection(ip, port, timeout=timeout)
        httpClient.request("POST", reqAddr, params, headers)
        #log.info("Http Send:  " + str(data))\
        print("Http Send:  " + str(data))
        response = httpClient.getresponse()
        if (response.status == 200):
            content = response.read().decode("utf-8")
            print("Http Recv:  " + content)
            data = json.loads(content)
            return  data["status"]
        else:
            return 0

    except Exception, e:
        print e
        return -1
    finally:
        if httpClient:
            httpClient.close()

# 配合PyUnit测试封装的表单请求,请求方式为POST,默认返回如下：
# {"status":100,"unixTime":1489041578090,"error":null,"data":{"adminId":226,"adminCode":"autoTest","passwd":"14e1b600b1fd579f47433b88e8d85291","adminName":"范训山","companyId":162,"status":1,"onlineFlag":0,"mobile":"18758038709","createDatetime":1488790686000,"permissions":"1,2,3,4,5,6,7,8,9,11,12,13,14,25,26,27","levels":1,"version":"1.0.0"}}
# 函数返回调整为：请求发起成功的情况下返回请求状态，请求失败返回-1
def FormHttpPostFirst(url, data, logToTest=0):
    try:
        dataEncode = urllib.urlencode(data)
        req = urllib2.Request(url, dataEncode)
        fd = urllib2.urlopen(req)
        response = fd.read()
        print response
        if logToTest != 0:
            log.TestLog(str(response).decode("utf-8"))
        return json.loads(response)["status"]
    except Exception, e:
        log.error(str(e))
        return -1

# 配合账号新增工具，请求方式为GET
def FormHttpGet_returnData(url, data):
    try:
        getString = url + "?" + urllib.urlencode(data)
        req = urllib2.Request(getString)
        fd = urllib2.urlopen(req)
        response = fd.read()
        return  json.loads(response)
    except Exception, e:
        log.error(str(e))
        return {"status":-1}

# 配合账号新增工具，请求方式为POST
def FormHttpPostFirst_returnData(url, data):
    try:
        dataEncode = urllib.urlencode(data)
        req = urllib2.Request(url, dataEncode)
        fd = urllib2.urlopen(req)
        response = fd.read()
        return json.loads(response)
    except Exception, e:
        log.error(str(e))
        return {"status":-1}

# 配合PyUnit测试封装的表单请求,请求方式为POST
def FormHttpPost(url, data, logToTest=0):
    try:
        dataEncode = urllib.urlencode(data)
        req = urllib2.Request(url, dataEncode)
        fd = urllib2.urlopen(req)
        response = fd.read()
        print response
        if logToTest != 0:
            log.TestLog(str(response).decode("utf-8"))
        return json.loads(response)["status"]
    except Exception, e:
        print e
        log.error(str(e))
        return -1

# 配合PyUnit测试封装的表单请求，请求方式为POST，默认返回为{"valid":true}，函数返回调整为：成功返回100，失败返回0，错误返回-1
def FormHttpPostCheck(url,data):
    try:
        dataEncode = urllib.urlencode(data)
        req = urllib2.Request(url, dataEncode)
        fd = urllib2.urlopen(req)
        response = fd.read()
        print response
        result = json.loads(response)["valid"]
        if result == True:
            return 100
        else:
            return 0
    except Exception, e:
        log.error(str(e))
        return -1

# 配合PyUnit测试封装的表单请求，请求方式为GET
def FormHttpGet(url, data):
    try:
        getString = url + "?" + urllib.urlencode(data)
        req = urllib2.Request(getString)
        fd = urllib2.urlopen(req)
        response = fd.read()
        print response
        return json.loads(response)["status"]
    except Exception, e:
        print e
        log.error(str(e))
        return -1

# 配合PyUnit测试封装的表单请求,请求方式为DELETE
def FormHttpDelete(url, data, logToTest=0):
    try:
        dataEncode = urllib.urlencode(data)
        req = urllib2.Request(url, dataEncode)
        req.add_header('Content-Type', 'your/contenttype')
        req.get_method = lambda: 'DELETE'
        fd = urllib2.urlopen(req)
        response = fd.read()
        if logToTest != 0:
            log.TestLog(str(response).decode("utf-8"))
        return json.loads(response)["status"]
    except Exception, e:
        log.error(str(e))
        return -1

# 配合PyUnit测试封装，默认返回为页面，函数返回调整为：成功返回100，失败返回0，错误返回-1
def PageHttpGet(url, data):
    try:
        getString = url + "?" + urllib.urlencode(data)
        req = urllib2.Request(getString)
        fd = urllib2.urlopen(req)
        response = fd.read()
        regex=ur"</html>"
        if re.search(regex, response):
            return 100
        else:
            return 0
    except Exception, e:
        log.error(str(e))
        return -1

# 配合PyUnit测试封装，默认返回为页面，函数返回调整为：成功返回100，失败返回0，错误返回-1
def PageIdSearch(url, data, searchName):
    try:
        getString = url + "?" + urllib.urlencode(data)
        req = urllib2.Request(getString)
        fd = urllib2.urlopen(req)
        response = fd.read()

        index1 = response.index(searchName)
        str1 = response[:index1]
        index2 = str1.rindex('gradeX')
        str2 = str1[index2 + 12:]
        index3 = str2.index('">')
        str_id = str2[:index3]

        regex = ur"</html>"
        if re.search(regex, response):
            return {'status':100,'id':str_id}
        else:
            return {'status':0,'id':''}
    except Exception, e:
        log.error("PageIdSearch find error: "+str(e))
        return {'status':-1,'id':''}

# 配合增加用户工具的实现，获取页面中的群组id
'''
def PageGroupIdGet(url, data):
    try:
        getString = url + "?" + urllib.urlencode(data)
        req = urllib2.Request(getString)
        fd = urllib2.urlopen(req)
        response = fd.read()

        index1 = response.index(searchName)
        str1 = response[:index1]
        index2 = str1.rindex('gradeX')
        str2 = str1[index2 + 12:]
        index3 = str2.index('">')
        str_id = str2[:index3]

        regex = ur"</html>"
        if re.search(regex, response):
            return {'status':100,'id':str_id}
        else:
            return {'status':0,'id':''}
    except Exception, e:
        log.error("PageIdSearch find error: "+str(e))
        return {'status':-1,'id':''}
'''

#########################################
# 配合压力测试封装的表单请求，请求方式为Post，清除了log的打印
def pressure_formHttpPost(url, data):
    try:
        dataEncode  = urllib.urlencode(data)
        req         = urllib2.Request(url, dataEncode)
        fd          = urllib2.urlopen(req)
        response    = fd.read()
        #log.TestLog(str(response))
    except Exception, e:
        log.error("Error is occur in pressure_formHttpPost:\t"+str(e))
        return {"status":-1}

    try:
        result = json.loads(response)
        return result
    except Exception, e:
        log.error("Error is occur in pressure_formHttpPost:\t"+str(e))
        return {"status":0}

# 配合压力测试封装的表单请求,请求方式为DELETE，清除了log的打印
def pressure_formHttpDelete(url, data):
    try:
        dataEncode  = urllib.urlencode(data)
        req         = urllib2.Request(url, dataEncode)
        req.add_header('Content-Type', 'your/contenttype')
        req.get_method = lambda: 'DELETE'
        fd          = urllib2.urlopen(req)
        response    = fd.read()
    except Exception, e:
        log.error(u"Error is occur in pressure_formHttpDelete:\t"+str(e))
        return {"status":-1}

    try:
        result = json.loads(response)
        return result
    except Exception, e:
        log.error(u"Error is occur in pressure_formHttpDelete:\t"+ str(e))
        return {"status":0}

# 配合压力测试封装的表单请求，请求方式为POST，清除了log的打印
def pressure_fnHttpPost_app(ip, port, reqAddr, data):
    timeout = 300
    httpClient = None

    try:
        params = urllib.urlencode(data)
        headers = {"Content-type": "application/x-www-form-urlencoded; charset=UTF-8", "Accept": "application/json; charset=UTF-8"}

        httpClient = httplib.HTTPConnection(ip, port, timeout=timeout)
        httpClient.request("POST", reqAddr, params, headers)

        response = httpClient.getresponse(102400)
        if (response.status == 200):
            dataAck = response.read()
            return {"status": "success", "content": json.loads(dataAck)}

        else:
            dataAck = str(response.status)+":"+response.reason
            return {"status": "fail", "content": dataAck}
    except Exception, e:
        return {"status": "error", "content": e}
    finally:
        if httpClient:
            httpClient.close()

# 配合压力测试封装的表单请求，请求方式为POST，数据类型为text
def pressure_fnHttpPost(ip, port, reqAddr, data):
    timeout = 300
    httpClient = None

    try:
        params = urllib.urlencode(data)
        headers = {"Content-type": "application/x-www-form-urlencoded; charset=UTF-8","Accept": "text/json; charset=UTF-8"}

        httpClient = httplib.HTTPConnection(ip, port, timeout=timeout)
        httpClient.request("POST", reqAddr, params, headers)
        response = httpClient.getresponse(102400)
        if (response.status == 200):
            dataAck = response.read(102400)
            return {"status": "success", "content": json.loads(dataAck)}
        else:
            dataAck = str(response.status) + ":" + response.reason
            return {"status": "fail", "content": dataAck}
    except Exception, e:
        return {"status": "error", "content": e}
    finally:
        if httpClient:
            httpClient.close()

# 配合压力测试封装的表单请求,请求方式为POST
def FormHttpPost_normalAck(url, data, logToTest=0):
    try:
        log.TestLog(("Http Send:==========>" + "\n\turl:\t" + str(url) + "\n\tdata:\t" + str(data) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
        dataEncode = urllib.urlencode(data)
        req = urllib2.Request(url, dataEncode)
        fd = urllib2.urlopen(req)
        response = fd.read()
        try:
            result = json.loads(response)
            if logToTest != 0:
                log.TestLog(("Http  Ack:<==========\n\t" + "data:\t" + str(result) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
        except Exception, e:
            log.error(u"返回结果不是字典类型" + response+u"\n\t错误："+str(e))
        return json.loads(response)
    except Exception, e:
        log.error(u"FormHttpPost_normalAck运行报错："+str(e))
        return {"status":-1}

# 配合压力测试封装的表单请求,请求方式为DELETE
def FormHttpDelete_normalAck(url, data, logToTest=0):
    try:
        log.TestLog(("Http Send:==========>" + "\n\turl:\t" + str(url) + "\n\tdata:\t" + str(data) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
        dataEncode = urllib.urlencode(data)
        req = urllib2.Request(url, dataEncode)
        req.add_header('Content-Type', 'your/contenttype')
        req.get_method = lambda: 'DELETE'
        fd = urllib2.urlopen(req)
        response = fd.read()
        try:
            result = json.loads(response)
            print response
            if logToTest != 0:
                log.TestLog(("Http  Ack:<==========\n\t" + "data:\t" + str(result) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
        except Exception, e:
            log.error(u"返回结果不是字典类型" + response+u"\n\t错误："+str(e))
        return json.loads(response)
    except Exception, e:
        log.error(str(e))
        return {"status":-1}

# 对讲机数据交互方法封装,application
def Simulation_fnHttpPost_app(ip, port, reqAddr, data):
    timeout = 3000
    httpClient = None

    try:
        params = urllib.urlencode(data)
        headers = {"Content-type": "application/x-www-form-urlencoded; charset=UTF-8", "Accept": "application/json; charset=UTF-8"}

        httpClient = httplib.HTTPConnection(ip, port, timeout=timeout)
        httpClient.request("POST", reqAddr, params, headers)
        log.info("Http Send:  " + str(data))
        log.TestLog(("Http Send:==========>" + "\n\tdata:\t" + str(data)+ "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))

        response = httpClient.getresponse()
        if (response.status == 200):
            dataAck = response.read()
            log.info("Http Recv:  " + dataAck.decode("utf-8"))
            log.TestLog(("Http  Ack:<==========\n\t" + "data_true:\t" + str(dataAck) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
            return {"status": "success", "content": json.loads(dataAck)}

        else:
            dataAck = str(response.status)+":"+response.reason
            log.info(("Http  Ack:<==========\n\t" + "data_false:\t" + str(dataAck) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
            log.TestLog(("Http  Ack:<==========\n\t" + "data_false:\t" + str(dataAck) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
            return {"status": "fail", "content": dataAck}
    except Exception, e:
        log.info(("Http  Ack:<==========\n\t" + "data_error:\t" + str(e) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
        log.TestLog(("Http  Ack:<==========\n\t" + "data_error:\t" + str(e) + "\n\ttime:\t" + str(getTimeNow())).decode("utf-8"))
        return {"status": "error", "content": e}
    finally:
        if httpClient:
            httpClient.close()

# WebSocket通信类的实现
class webSocket():
    def __init__(self, cpu, destip, destport, destpath, cmpid, uid, pwd, key):
        self.cpu = cpu
        self.destip = destip
        self.destport = destport
        self.destpath = destpath
        self.token = None
        self.startTime_init = 0
        self.endTime_init = 0
        self.startTime_tcpIn = 0
        self.endTime_tcpIn = 0
        self.startTime_heart = 0
        self.endTime_heart = 0
        self.startTIme_inChannel = 0
        self.endTime_inChannel = 0
        self.statCon = False
        self.statTcpIn = False
        self.statHeart = False
        self.statInChannel = False
        self.statHasChannel = False

        self.idSingleCall = 0
        self.idBroadcast = 0
        self.idTempGroup = 0

        self.statSingleCall = False
        self.statTempGroup = False
        self.statBroadcast = False
        self.channelType = 1

        self.ws = None
        self.cmpid = cmpid
        self.uid = uid

        self.pwd = pwd
        self.key = key
        self.cid = None
        self.sid = None
        self.aip = None
        self.aport = None

        self.isInitFlag = False
        self.recvPtt = ""
        self.isInit = False

        self.pttKey = ""

        self.event = threading.Event()
        self.recvCmd = None

        self.startTime_init = time.time()
        self.thread_websocket = threading.Thread(target=self.create_websocket, args=())
        self.thread_websocket.start()

        self.thread_recvCmdHandler = threading.Thread(target=self.recvCmdHandler, args=(cpu,self))
        self.thread_recvCmdHandler.start()

        time.sleep(1)

    def create_websocket(self):
        self.ws = websocket.WebSocketApp('ws://'+self.destip+':'+str(self.destport)+'/'+self.destpath)
        self.isInit = True
        self.ws.on_message = self.on_message
        self.ws.on_error = self.on_error
        self.ws.on_close = self.on_close
        self.ws.on_open = self.on_open
        self.ws.run_forever()

    def wsTcpSend(self, msg, flag=1):
        self.ws.send(str(msg))
        if flag == 1:
            log.info("WS   Send:  " + str(msg))

    def recvCmdHandler(self, cpu, websocket):
        while True:
            # 等待事件，进入等待阻塞状态
            log.info('wait for event...')
            websocket.event.wait()

            # 收到事件后进入运行状态
            log.info('recv event')

            if websocket.recvCmd == 8:
                log.info("WebSocket recv 8, start to enter singleCall...")
                websocket.wsTcpSend(assemblyTCPData(3, 1, 1, getInVoiceChannelMsg(websocket.cmpid, websocket.uid, websocket.idSingleCall, websocket.cpu["data"]._const["CHANNEL_TYPE"]["singleCall"])))
                while True:
                    if (websocket.statSingleCall == True):
                        websocket.statInChannel = False
                        log.info("WebSocket recv 8, success to enter singleCall...")
                        websocket.wsTcpSend(assemblyTCPData(8008, 1, 0, getVideoSingleCallMsg_server(2, 0, websocket.idSingleCall, websocket.uid)))
                        break
                    else:
                        time.sleep(0.001)

            elif websocket.recvCmd == 12:
                log.info("WebSocket recv 12, start to back intercom...")
                websocket.wsTcpSend(assemblyTCPData(3, 1, 1, getInVoiceChannelMsg(websocket.cmpid, websocket.uid, websocket.cpu["data"]._const["simulationTest"]["bakIntercomGroup"], websocket.cpu["data"]._const["CHANNEL_TYPE"]["intercom"])))
                while True:
                    if (websocket.statInChannel == True):
                        websocket.statSingleCall = False
                        log.info("WebSocket recv 12, success to back intercom...")
                        websocket.wsTcpSend(assemblyTCPData(8012, 1, 0, getVideoCallHangUpMsg_server(0, 0, '', websocket.cid, websocket.sid, websocket.cpu["data"]._const["simulationTest"]["bakIntercomGroup"])))
                        break
                    else:
                        time.sleep(0.001)
            elif websocket.recvCmd == 17:
                log.info("WebSocket recv 17, start to enter broadcast...")
                websocket.wsTcpSend(assemblyTCPData(3, 1, 1, getInVoiceChannelMsg(websocket.cmpid, websocket.uid, websocket.idBroadcast, websocket.cpu["data"]._const["CHANNEL_TYPE"]["broadcast"])))
                while True:
                    if (websocket.statBroadcast == True):
                        websocket.statInChannel = False
                        log.info("Websocket recv 17, success to enter intercom...")
                        websocket.wsTcpSend(assemblyTCPData(8017, 1, 0, getBoardcastMsg_sever(2, 0, websocket.idBroadcast, websocket.uid)))
                        break
                    else:
                        time.sleep(0.001)
            elif websocket.recvCmd == 19:
                log.info("WebSocket recv 19, start to back intercom...")
                websocket.wsTcpSend(assemblyTCPData(3, 1, 1, getInVoiceChannelMsg(websocket.cmpid, websocket.uid, websocket.cpu["data"]._const["simulationTest"]["bakIntercomGroup"], websocket.cpu["data"]._const["CHANNEL_TYPE"]["intercom"])))
                while True:
                    if (websocket.statInChannel == True):
                        websocket.statBroadcast = False
                        log.info("WebSocket recv 19, success to back intercom...")
                        websocket.wsTcpSend(assemblyTCPData(8019, 1, 0, geBoardcastHangUpMsg_server(0, 0, websocket.cpu["data"]._const["simulationTest"]["bakIntercomGroup"], websocket.uid)))
                        break
                    else:
                        time.sleep(0.001)
            elif websocket.recvCmd == 21:
                log.info("WebSocket recv 21, start to enter tempGroup...")
                websocket.wsTcpSend(assemblyTCPData(3, 1, 1, getInVoiceChannelMsg(websocket.cmpid, websocket.uid, websocket.idTempGroup, websocket.cpu["data"]._const["CHANNEL_TYPE"]["tempGroup"])))

                while True:
                    if (self.statTempGroup == True):
                        self.statInChannel = False
                        log.info("WebSocket recv 21, success to enter tempGroup...")
                        self.wsTcpSend(assemblyTCPData(8021, 1, 0, getTemporaryTalkMsg_server(2, 0, self.idTempGroup, self.uid)))
                        break
                    else:
                        time.sleep(0.001)
            elif websocket.recvCmd == 23:
                log.info("WebSocket recv 23, start to back intercom...")
                websocket.wsTcpSend(assemblyTCPData(3, 1, 1, getInVoiceChannelMsg(websocket.cmpid, websocket.uid, websocket.cpu["data"]._const["simulationTest"]["bakIntercomGroup"], websocket.cpu["data"]._const["CHANNEL_TYPE"]["intercom"])))

                while True:
                    if (self.statInChannel == True):
                        self.statTempGroup = False
                        log.info("WebSocket recv 23, success to back intercom...")
                        self.wsTcpSend(assemblyTCPData(8023, 1, 0, getTemporaryTalkHangUpMsg_server(2, 0, self.cpu["data"]._const["simulationTest"]["bakIntercomGroup"])))
                        break
                    else:
                        time.sleep(0.001)

            websocket.event.clear()

    def close(self):
        self.ws.close()

    def on_message(self,ws,data):
        try:
            if ws:
                msg = json.loads(data)
                if msg["body"]:
                    cmd = msg["cmd"]
                    if cmd != 8002 and cmd != 15: #8002为心跳包
                    #if cmd != 15: #8002为心跳包
                        log.info("WS   Recv:  " + str(data))

                    if cmd == 15: #推送信息进行屏蔽
                        pass
                    elif cmd == 8:
                        log.TestLog("WebSocket recv 8")
                        self.idSingleCall = msg["body"]["gid"]
                        self.recvCmd = cmd
                        self.event.set()
                    elif cmd == 12:
                        log.TestLog("WebSocket recv 12")
                        self.recvCmd = cmd
                        self.event.set()
                    elif cmd == 17:
                        log.TestLog("WebSocket recv 17")
                        self.idBroadcast = msg["body"]["gid"]
                        self.recvCmd = cmd
                        self.event.set()
                    elif cmd == 19:
                        log.TestLog("WebSocket recv 19")
                        self.recvCmd = cmd
                        self.event.set()
                    elif cmd == 21:
                        log.TestLog("WebSocket recv 21")
                        self.idTempGroup = msg["body"]["gid"]
                        self.recvCmd = cmd
                        self.event.set()
                    elif cmd == 23:
                        log.TestLog("WebSocket recv 23")
                        self.recvCmd = cmd
                        self.event.set()
                    elif cmd == 8001:
                        if self.endTime_tcpIn == 0:
                            self.endTime_tcpIn = time.time()
                        if msg["body"]["err"] == 0:
                            self.token = msg["body"]["token"]
                            self.statTcpIn = True
                    elif cmd == 8002:
                        if self.endTime_heart == 0:
                            self.endTime_heart = time.time()
                        if msg["body"]["err"] == 0 and self.statHeart == False:
                            self.statHeart = True
                    elif cmd == 8003:
                        if self.endTime_inChannel == 0:
                            self.endTime_inChannel = time.time()

                        self.cid = msg["body"]["cid"]
                        self.sid = msg["body"]["sid"]
                        self.aip = msg["body"]["aip"]
                        self.aport = msg["body"]["aport"]

                        if msg["body"]["err"] == 0:
                            if msg["body"]["type"] == 5:
                                self.statTempGroup = True
                                self.statInChannel = True
                                log.info("The intercom status is tempGroup")
                            elif msg["body"]["type"] == 4:
                                self.statSingleCall = True
                                self.statInChannel = True
                                log.info("The intercom status is singleCall")
                            elif msg["body"]["type"] == 3:
                                self.statBroadcast = True
                                self.statInChannel = True
                                log.info("The intercom status is broadcast")
                            elif msg["body"]["type"] == 2:
                                pass
                            elif msg["body"]["type"] == 1:
                                self.statInChannel = True
                                log.info("The intercom status is channel")
                            else:
                                log.info("The channel type is not the right num!")

                    elif cmd == 8004:
                        try:
                            if msg["body"]["err"] == 0:
                                self.statInChannel = False
                        except Exception, e:
                            log.error(str(e))
                    elif cmd == 8005:
                        try:
                            if msg["body"]["err"] == 0:
                                self.statSingleCall = False
                        except Exception, e:
                            log.error(str(e))
                    elif cmd == 6:    # 单呼挂断
                        print("Start the callback for " + str(cmd))
                    elif cmd == 8007:
                        try:
                            if msg["body"]["err"] == 0:
                                self.statSingleCall = True
                        except Exception, e:
                            log.error(str(e))
                    elif cmd == 8013: # 断线
                        if self.endTime_inChannel == 0:
                            self.endTime_inChannel = time.time()

                        if msg["body"]["err"] == 0:
                            self.statHasChannel = True

                        self.cid = msg["body"]["cid"]
                        self.sid = msg["body"]["sid"]
                        self.aip = msg["body"]["aip"]
                        self.aport = msg["body"]["aport"]
                        self.gid = msg["body"]["gid"]

                        if msg["body"]["err"] == 0:
                            self.channelType = msg["body"]["type"]
                            if msg["body"]["type"] == 5:
                                self.statTempGroup = True
                                self.statInChannel = True
                                log.TestLog("The intercom status is tempGroup")
                            elif msg["body"]["type"] == 4:
                                self.statSingleCall = True
                                self.statInChannel = True
                                log.TestLog("The intercom status is singleCall")
                            elif msg["body"]["type"] == 3:
                                self.statBroadcast = True
                                self.statInChannel = True
                                log.TestLog("The intercom status is broadcast")
                            elif msg["body"]["type"] == 2:
                                pass
                            elif msg["body"]["type"] == 1:
                                self.statInChannel = True
                                log.TestLog("The intercom status is channel")
                            else:
                                log.TestLog("The channel type is not the right num!")

                    elif cmd == 8014:
                        print("Start the callback for " + str(cmd))
                    elif cmd == 8016:
                        try:
                            if msg["body"]["err"] == 0:
                                self.statBroadcast = True
                                self.broadcastGid = msg["body"]["gid"]
                        except Exception, e:
                            log.error(str(e))
                    elif cmd == 8018: # 广播结束
                        try:
                            if msg["body"]["err"] == 0:
                                self.statBroadcast = False
                        except Exception, e:
                            log.error(str(e))
                    elif cmd == 8020:
                        try:
                            if msg["body"]["err"] == 0:
                                self.statTempGroup = True
                        except Exception, e:
                            log.error(str(e))
                    elif cmd == 8022:
                        try:
                            if msg["body"]["err"] == 0:
                                self.statTempGroup = False
                        except Exception, e:
                            log.error(str(e))
                    elif cmd == 24:   #退出媒体通知
                        print("Start the callback for " + str(cmd))
                    elif cmd == 9001: #上线
                        fnTcp_clientOnlineHandler(self.cpu, msg["body"])
                    elif cmd == 9002: #下线
                        fnTcp_clientOutlineHandler(self.cpu, msg["body"])
                    elif cmd == 9003: #加入群组
                        fnTcp_clientJoinGroupHandler(self.cpu, msg["body"])
                    elif cmd == 10101:  # 管理台信令
                        log.info("Start the callback for " + str(cmd))
                    elif cmd == 10102:
                        log.info("Start the callback for " + str(cmd))
                    elif cmd == 10103:
                        log.info("Start the callback for " + str(cmd))
                    elif cmd == 10104:
                        log.info("Start the callback for " + str(cmd))
                    elif cmd == 10201:
                        log.info("Start the callback for " + str(cmd))
                    elif cmd == 10202:
                        log.info("Start the callback for " + str(cmd))
                    elif cmd == 10203:
                        log.info("Start the callback for " + str(cmd))
                    elif cmd == 10301:
                        log.info("Start the callback for " + str(cmd))
                    elif cmd == 10302:
                        log.info("Start the callback for " + str(cmd))
                    else:
                        log.info("Start the callback for " + str(cmd))
            else:
                log.info("WebSocket is not exist!")
        except Exception, e:
            log.error(str(e))

    def on_error(self,ws,error):
        log.error(str(error))

    def on_open(self,ws):
        self.endTime_init = time.time()
        self.statCon = True

    def on_close(self,ws):
        self.statCon = False

# 配合压力测试log方面调整后实现的WebSocket
class pressure_webSocket():
    def __init__(self, cpu, destip, destport, destpath, cmpid, uid, pwd, key):
        self.cpu = cpu
        self.udpsocket = None
        self.token = None
        self.startTime_init = 0
        self.endTime_init = 0
        self.startTime_tcpIn = 0
        self.endTime_tcpIn = 0
        self.startTime_heart = 0
        self.endTime_heart = 0
        self.startTIme_inChannel = 0
        self.endTime_inChannel = 0
        self.statCon = False
        self.statTcpIn = False
        self.statHeart = False
        self.statInChannel = False

        self.idSingleCall = 0
        self.idBroadcast = 0
        self.idTempGroup = 0

        self.statSingleCall = False
        self.statTempGroup = False
        self.statBroadcast = False
        self.channelType = 1

        self.ws = None
        self.cmpid = cmpid
        self.uid = uid
        self.pwd = pwd
        self.key = key
        self.cid = None
        self.sid = None
        self.gid = 0
        self.intercomType = None

        self.destip = destip
        self.destport = destport
        self.destpath = destpath

        self.event = threading.Event()
        self.recvCmd = None

        self.startTime_init = time.time()
        self.thread_websocket = threading.Thread(target=self.create_websocket, args=())
        self.thread_websocket.start()

        self.thread_recvCmdHandler = threading.Thread(target=self.recvCmdHandler, args=(cpu,self))
        self.thread_recvCmdHandler.start()

        self.thread_heartbeatRtp = None

        time.sleep(1)

    def create_websocket(self):
        self.ws = websocket.WebSocketApp('ws://'+self.destip+':'+str(self.destport)+'/'+self.destpath)
        self.ws.on_message = self.on_message
        self.ws.on_error = self.on_error
        self.ws.on_close = self.on_close
        self.ws.on_open = self.on_open
        self.ws.run_forever()

    def wsTcpSend(self, msg, flag=0):
        self.ws.send(str(msg))
        if flag == 1:
            log.info("WS   Send:  " + str(msg))

    def recvCmdHandler(self, cpu, websocket):
        while True:
            # 等待事件，进入等待阻塞状态
            #log.info('wait for event...')
            websocket.event.wait()

            # 收到事件后进入运行状态
            log.info('recv event')

            if websocket.recvCmd == 8:
                log.info("WebSocket recv 8, start to enter singleCall...")
                websocket.wsTcpSend(assemblyTCPData(3, 1, 1, getInVoiceChannelMsg(websocket.cmpid, websocket.uid, websocket.idSingleCall, websocket.cpu["data"]._const["CHANNEL_TYPE"]["singleCall"])))
                while True:
                    if (websocket.statSingleCall == True):
                        websocket.statInChannel = False
                        log.info("WebSocket recv 8, success to enter singleCall...")
                        websocket.wsTcpSend(assemblyTCPData(8008, 1, 0, getVideoSingleCallMsg_server(2, 0, websocket.idSingleCall, websocket.uid)))
                        break
                    else:
                        time.sleep(0.001)

            elif websocket.recvCmd == 12:
                log.info("WebSocket recv 12, start to back intercom...")
                websocket.wsTcpSend(assemblyTCPData(3, 1, 1, getInVoiceChannelMsg(websocket.cmpid, websocket.uid, websocket.cpu["data"]._const["simulationTest"]["bakIntercomGroup"], websocket.cpu["data"]._const["CHANNEL_TYPE"]["intercom"])))
                while True:
                    if (websocket.statInChannel == True):
                        websocket.statSingleCall = False
                        log.info("WebSocket recv 12, success to back intercom...")
                        websocket.wsTcpSend(assemblyTCPData(8012, 1, 0, getVideoCallHangUpMsg_server(0, 0, '', websocket.cid, websocket.sid, websocket.cpu["data"]._const["simulationTest"]["bakIntercomGroup"])))
                        break
                    else:
                        time.sleep(0.001)
            elif websocket.recvCmd == 17:
                log.info("WebSocket recv 17, start to enter broadcast...")
                websocket.wsTcpSend(assemblyTCPData(3, 1, 1, getInVoiceChannelMsg(websocket.cmpid, websocket.uid, websocket.idBroadcast, websocket.cpu["data"]._const["CHANNEL_TYPE"]["broadcast"])))
                while True:
                    if (websocket.statBroadcast == True):
                        websocket.statInChannel = False
                        log.info("Websocket recv 17, success to enter intercom...")
                        websocket.wsTcpSend(assemblyTCPData(8017, 1, 0, getBoardcastMsg_sever(2, 0, websocket.idBroadcast, websocket.uid)))
                        break
                    else:
                        time.sleep(0.001)
            elif websocket.recvCmd == 19:
                log.info("WebSocket recv 19, start to back intercom...")
                websocket.wsTcpSend(assemblyTCPData(3, 1, 1, getInVoiceChannelMsg(websocket.cmpid, websocket.uid, websocket.cpu["data"]._const["simulationTest"]["bakIntercomGroup"], websocket.cpu["data"]._const["CHANNEL_TYPE"]["intercom"])))
                while True:
                    if (websocket.statInChannel == True):
                        websocket.statBroadcast = False
                        log.info("WebSocket recv 19, success to back intercom...")
                        websocket.wsTcpSend(assemblyTCPData(8019, 1, 0, geBoardcastHangUpMsg_server(0, 0, websocket.cpu["data"]._const["simulationTest"]["bakIntercomGroup"], websocket.uid)))
                        break
                    else:
                        time.sleep(0.001)
            elif websocket.recvCmd == 21:
                log.info("WebSocket recv 21, start to enter tempGroup...")
                websocket.wsTcpSend(assemblyTCPData(3, 1, 1, getInVoiceChannelMsg(websocket.cmpid, websocket.uid, websocket.idTempGroup, websocket.cpu["data"]._const["CHANNEL_TYPE"]["tempGroup"])))

                while True:
                    if (self.statTempGroup == True):
                        self.statInChannel = False
                        log.info("WebSocket recv 21, success to enter tempGroup...")
                        self.wsTcpSend(assemblyTCPData(8021, 1, 0, getTemporaryTalkMsg_server(2, 0, websocket.idTempGroup, websocket.uid)))
                        break
                    else:
                        time.sleep(0.001)
            elif websocket.recvCmd == 23:
                log.info("WebSocket recv 23, start to back intercom...")
                websocket.wsTcpSend(assemblyTCPData(3, 1, 1, getInVoiceChannelMsg(websocket.cmpid, websocket.uid, websocket.cpu["data"]._const["simulationTest"]["bakIntercomGroup"], websocket.cpu["data"]._const["CHANNEL_TYPE"]["intercom"])))

                while True:
                    if (self.statInChannel == True):
                        self.statTempGroup = False
                        log.info("WebSocket recv 23, success to back intercom...")
                        self.wsTcpSend(assemblyTCPData(8023, 1, 0, getTemporaryTalkHangUpMsg_server(2, 0, websocket.cpu["data"]._const["simulationTest"]["bakIntercomGroup"])))
                        break
                    else:
                        time.sleep(0.001)
            elif websocket.recvCmd == 24:
                log.info("WebSocket recv 24, start to back intercom...")
                websocket.wsTcpSend(assemblyTCPData(3, 1, 1, getInVoiceChannelMsg(websocket.cmpid, websocket.uid, websocket.gid, websocket.intercomType)))
            websocket.event.clear()

    def close(self):
        self.ws.close()

    def on_message(self,ws,data):
        try:
            if ws:
                msg = json.loads(data)
                if msg["body"]:
                    cmd = msg["cmd"]
                    #if cmd != 8002 and cmd != 15: #8002为心跳包
                    #if cmd != 15: #8002为心跳包
                    #    log.info("WS   Recv:  " + str(data))

                    if cmd == 15: #推送信息进行屏蔽
                        pass
                    elif cmd == 8:
                        log.TestLog("WebSocket recv 8")
                        self.idSingleCall = msg["body"]["gid"]
                        self.recvCmd = cmd
                        self.event.set()
                    elif cmd == 12:
                        log.TestLog("WebSocket recv 12")
                        self.recvCmd = cmd
                        self.event.set()
                    elif cmd == 17:
                        log.TestLog("WebSocket recv 17")
                        self.idBroadcast = msg["body"]["gid"]
                        self.recvCmd = cmd
                        self.event.set()
                    elif cmd == 19:
                        log.TestLog("WebSocket recv 19")
                        self.recvCmd = cmd
                        self.event.set()
                    elif cmd == 21:
                        log.TestLog("WebSocket recv 21")
                        self.idTempGroup = msg["body"]["gid"]
                        self.recvCmd = cmd
                        self.event.set()
                    elif cmd == 23:
                        log.TestLog("WebSocket recv 23")
                        self.recvCmd = cmd
                        self.event.set()
                    elif cmd == 24:
                        log.TestLog("WebSocket recv 24")

                        self.cid = msg["body"]["cid"]
                        self.sid = msg["body"]["sid"]
                        self.gid = msg["body"]["gid"]
                        self.uid = msg["body"]["uid"]
                        self.intercomType = msg["body"]["type"]

                        self.recvCmd = cmd
                        self.event.set()
                    elif cmd == 8001:
                        if self.endTime_tcpIn == 0:
                            self.endTime_tcpIn = time.time()
                        if msg["body"]["err"] == 0:
                            self.token = msg["body"]["token"]
                            self.statTcpIn = True
                    elif cmd == 8002:
                        if self.endTime_heart == 0:
                            self.endTime_heart = time.time()
                        if msg["body"]["err"] == 0 and self.statHeart == False:
                            self.statHeart = True
                    elif cmd == 8003:
                        log.info("WebSocket recv " + str(cmd))
                        if self.endTime_inChannel == 0:
                            self.endTime_inChannel = time.time()

                        self.cid = msg["body"]["cid"]
                        self.sid = msg["body"]["sid"]
                        self.aip = msg["body"]["aip"]
                        self.aport = msg["body"]["aport"]

                        if msg["body"]["err"] == 0:
                            if msg["body"]["type"] == 5:
                                self.statTempGroup = True
                                self.statInChannel = True
                                log.info("The intercom status is tempGroup")
                            elif msg["body"]["type"] == 4:
                                self.statSingleCall = True
                                self.statInChannel = True
                                log.info("The intercom status is singleCall")
                            elif msg["body"]["type"] == 3:
                                self.statBroadcast = True
                                self.statInChannel = True
                                log.info("The intercom status is broadcast")
                            elif msg["body"]["type"] == 2:
                                pass
                            elif msg["body"]["type"] == 1:
                                self.statInChannel = True
                                log.info("The intercom status is channel")
                            else:
                                log.info("The channel type is not the right num!")

                        if self.udpsocket == None:
                            log.info("aip:"+str(self.aip)+" aport:"+str(self.aport)+" sid:"+str(self.sid)+" cid:"+str(self.cid)+" uid:"+str(self.uid))
                            rtpData = getRtpPackage(self.sid, self.cid, self.uid)
                            self.udpsocket = udpSocket(self.aip, self.aport, rtpData)
                            self.thread_heartbeatRtp = threading.Thread(target=heartbeatRtp, args=(self.udpsocket,))
                            self.thread_heartbeatRtp.start()
                        else:
                            log.info("aip:"+str(self.aip)+" aport:"+str(self.aport)+" sid:"+str(self.sid)+" cid:"+str(self.cid)+" uid:"+str(self.uid))
                            rtpData = getRtpPackage(self.sid, self.cid, self.uid)
                            self.udpsocket.update(self.aip, self.aport, rtpData)
                            
                    elif cmd == 8004:
                        try:
                            if msg["body"]["err"] == 0:
                                self.statInChannel = False
                        except Exception, e:
                            log.error(str(e))
                    elif cmd == 8005:
                        try:
                            if msg["body"]["err"] == 0:
                                self.statSingleCall = False
                        except Exception, e:
                            log.error(str(e))
                    elif cmd == 6:    # 单呼挂断
                        log.info("Start the callback for " + str(cmd))
                    elif cmd == 8007:
                        try:
                            if msg["body"]["err"] == 0:
                                self.statSingleCall = True
                        except Exception, e:
                            log.error(str(e))
                    elif cmd == 8013: # 断线
                        log.info("Start the callback for " + str(cmd))
                        if self.endTime_inChannel == 0:
                            self.endTime_inChannel = time.time()

                        #if msg["body"]["err"] == 0:
                        #    self.statHasChannel = True

                        #self.cid = msg["body"]["cid"]
                        #self.sid = msg["body"]["sid"]
                        #self.aip = msg["body"]["aip"]
                        #self.aport = msg["body"]["aport"]
                        self.gid = msg["body"]["gid"]

                        if msg["body"]["err"] == 0:
                            self.channelType = msg["body"]["type"]
                            log.info("Recv 8013, exit login..., the channel type is:"+str(self.channelType)+" the group id is:"+str(self.gid))
                            if msg["body"]["type"] == 5:
                                self.statTempGroup = True
                                self.statInChannel = True
                                log.info("The intercom status is tempGroup")
                            elif msg["body"]["type"] == 4:
                                self.statSingleCall = True
                                self.statInChannel = True
                                log.info("The intercom status is singleCall")
                            elif msg["body"]["type"] == 3:
                                self.statBroadcast = True
                                self.statInChannel = True
                                log.info("The intercom status is broadcast")
                            elif msg["body"]["type"] == 2:
                                pass
                            elif msg["body"]["type"] == 1:
                                self.statInChannel = True
                                log.info("The intercom status is channel")
                            else:
                                log.info("The channel type is not the right num!")

                    elif cmd == 8014:
                        log.info("Start the callback for " + str(cmd))
                    elif cmd == 8016:
                        try:
                            if msg["body"]["err"] == 0:
                                self.statBroadcast = True
                                self.broadcastGid = msg["body"]["gid"]
                        except Exception, e:
                            log.error(str(e))
                    elif cmd == 8018: # 广播结束
                        try:
                            if msg["body"]["err"] == 0:
                                self.statBroadcast = False
                        except Exception, e:
                            log.error(str(e))
                    elif cmd == 8020:
                        try:
                            if msg["body"]["err"] == 0:
                                self.statTempGroup = True
                        except Exception, e:
                            log.error(str(e))
                    elif cmd == 8022:
                        try:
                            if msg["body"]["err"] == 0:
                                self.statTempGroup = False
                        except Exception, e:
                            log.error(str(e))
                    elif cmd == 9001: #上线
                        fnTcp_clientOnlineHandler(self.cpu, msg["body"])
                    elif cmd == 9002: #下线
                        fnTcp_clientOutlineHandler(self.cpu, msg["body"])
                    elif cmd == 9003: #加入群组
                        fnTcp_clientJoinGroupHandler(self.cpu, msg["body"])
                    elif cmd == 10101: #管理台信令
                        log.info("Start the callback for " + str(cmd))
                    elif cmd == 10102:
                        log.info("Start the callback for " + str(cmd))
                    elif cmd == 10103:
                        log.info("Start the callback for " + str(cmd))
                    elif cmd == 10104:
                        log.info("Start the callback for " + str(cmd))
                    elif cmd == 10201:
                        log.info("Start the callback for " + str(cmd))
                    elif cmd == 10202:
                        log.info("Start the callback for " + str(cmd))
                    elif cmd == 10203:
                        log.info("Start the callback for " + str(cmd))
                    elif cmd == 10301:
                        log.info("Start the callback for " + str(cmd))
                    elif cmd == 10302:
                        log.info("Start the callback for " + str(cmd))
                    else:
                        log.info("Else...  Start the callback for " + str(cmd))
            else:
                log.info("WebSocket is not exist!")
        except Exception,e:
            log.error(str(e))

    def on_error(self,ws,error):
        log.error(str(error))

    def on_open(self,ws):
        self.endTime_init = time.time()
        self.statCon = True

    def on_close(self,ws):
        pass

# RtpSocket_bak通信类的实现
class rtpSocket():
    def __init__(self, cpu, destIP, destPort, destPath, localIP, localPort):
        self.cpu = cpu

        self.ws = None
        self.uid = None
        self.cid = None
        self.sid = None
        self.aip = None
        self.aport = None
        self.stat = None
        self.statCon = False
        self.statRtpIn = False
        self.statSendVoice = False

        self.destIP = destIP
        self.destPort = destPort
        self.destPath = destPath
        self.payloadtype = None
        self.localIP = localIP
        self.localPort = localPort
        self.sendflag = None

        self.recvPtt = 0
        self.isInit = False
        self.pttKey = None

        self.thread_rtpsocket = threading.Thread(target=self.create_rtpsocket, args=())
        self.thread_rtpsocket.start()

        time.sleep(1)

    def create_rtpsocket(self):
        url = 'ws://'+self.destIP+':'+str(self.destPort)+'/'+self.destPath
        log.info(u"rtpSocket链接为："+url)
        self.ws = websocket.WebSocketApp('ws://'+self.destIP+':'+str(self.destPort)+'/'+self.destPath)

        self.isInit = True
        self.ws.on_message = self.on_message
        self.ws.on_error = self.on_error
        self.ws.on_close = self.on_close
        self.ws.on_open = self.on_open
        #self.ws.run_forever(http_proxy_host=self.localIP, http_proxy_port=self.localPort)
        self.ws.run_forever()

    def send(self,message):
        log.info("RTP Send:  "+message)
        self.ws.send(message)

    def wsRtpSend(self, msg, flag=1):
        self.ws.send(str(msg))
        if flag == 1:
            log.info("RTP  Send:  " + str(msg))

    def accessRtp(self, cid, sid, uid, destip, destport, payloadtype, sendflag):
        json = getAccessRtpMsg(cid, sid, uid, destip, destport, payloadtype, sendflag)
        jsonstr = str(json).replace('\'','"')
        self.wsRtpSend(jsonstr)

    def startSendRtp(self, sid, cid, flag):
        json = getSendRtpMsg(sid, cid, flag)
        jsonstr = str(json).replace('\'', '"')
        self.wsRtpSend(jsonstr)

    def stopSendRtp(self, sid, cid):
        json = getStopRtpMsg(sid,cid)
        jsonstr = str(json).replace('\'', '"')
        self.wsRtpSend(jsonstr)

    def close(self):
        self.ws.close()

    def on_message(self,ws,data):
        if ws:
            msg = json.loads(data)
            if msg["cmd"]:
                cmd = msg["cmd"]
                log.info("RTP  Recv:  " + str(data))

                if cmd == 8001:
                    self.statRtpIn = True
                    #fnRtp_accessHandler()
                elif cmd == 8002:
                    self.statRtpIn = False
                    #fnRtp_stopRtpHandler()
                elif cmd == 8003:
                    if msg["sendflag"] == 1:
                        self.statSendVoice = True
                    else:
                        self.statSendVoice = False
                    #fnRtp_sendRtpHandler(self.cpu, msg)
                elif cmd == 4:
                    if msg["recvPtt"] == 1:
                        log.TestLog(u"收到RTP语音包！对讲机："+str(msg["uid"]))
                    else:
                        log.TestLog(u"结束Rtp语音包")
                    #fnRtp_recvPttHandler(self.cpu, msg)
                else:
                    pass
                    #fnRtp_otherHandler(self.cpu, msg)
        else:
            print("WebSocket is not exist!")

    def on_error(self,ws,error):
        log.error(str(error))

    def on_open(self,ws):
        log.info("========== RTP Service Open ==========")
        self.statCon = True

    def on_close(self,ws):
        log.info("========== RTP Service Close ==========")

# RtpSocket通信类的实现
class rtpSocket_bak():
    def __init__(self, cpu, destip, destport, destpath, uid):
        self.cpu = cpu

        self.ws = None
        self.uid = uid
        self.cid = None
        self.sid = None

        self.destip = destip
        self.destport = destport
        self.destpath = destpath
        self.payloadtype = None
        self.sendflag = None

        self.recvPtt = 0
        self.isInit = False
        self.pttKey = None

        self.udpClient = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)       #创建UDP套接字
        self.udpClient.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)	#设置重用套接字地址
        self.udpClient.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1)		#设置UDP允许广播
        self.udpClient.setblocking(0)											#将UDP套接字设置成非阻塞状态
        self.udpClient.settimeout(0.8)											#设置超时时间为0.8s
        self.udpClient.bind(('127.0.0.1', 54321))		#IP、Port绑定

    def RtpSend(self, msg, flag=1):
        self.udpClient.sendto(str(msg), (self.destip, self.destport))
        if flag == 1:
            log.info("WS   Send:  " + str(msg))
        data, addr = self.udpClient.recvfrom(1024)
        log.info("WS   Send:  " + str(data))

    def accessRtp(self, cid, sid, uid, destip, destport, payloadtype, sendflag):
        self.RtpSend(getAccessRtpMsg(cid, sid, uid, destip, destport, payloadtype, sendflag))

    def startSendRtp(self, sid, cid, flag):
        self.RtpSend(getSendRtpMsg(sid, cid, flag))

    def stopSendRtp(self, sid, cid):
        self.RtpSend(getStopRtpMsg(sid,cid))

    def close(self):
        self.ws.close()

    def exitRtp(self):
        if(self.cid and self.sid):
            self.send(self.getStopRtpMsg(self.sid, self.cid))

    def setPttKeyboard(self,code):
        self.pttKey = code

    def onPttKeyDown(self):
        self.startPtt()

    def onPttKeyUp(self):
        self.stopPtt()

    def offPttKey(self):
        pass

    def startPtt(self):
        self.startSendRtp()

    def stopPtt(self):
        self.stopSendRtp()

    def on_message(self,ws,data):
        try:
            if ws:
                msg = json.loads(data)
                if msg["body"]:
                    cmd = msg["cmd"]
                    if cmd == 8001:
                        fnRtp_accessHandler()
                    elif cmd == 8002:
                        fnRtp_stopRtpHandler()
                    elif cmd == 8003:
                        fnRtp_sendRtpHandler(self.cpu,msg["body"])
                    elif cmd == 4:
                        fnRtp_recvPttHandler(self.cpu,msg["body"])
                    else:
                        fnRtp_otherHandler(self.cpu,msg["body"])
            else:
                print("WebSocket is not exist!")
        except Exception,e:
            log.error(str(e))

    def on_error(self,ws,error):
        log.error(str(error))

    def on_open(self,ws):
        log.info("========== WS Service Open ==========")

    def on_close(self,ws):
        log.info("========== WS Service Close ==========")

# 临时组对讲结束：23——>8023
def getTemporaryTalkHangUpMsg_server(stat, err, gid):
    return {
        'stat':stat,
        'err':err,
        'gid':gid
    }
    pass

# 临时组对讲：21——>8021（server）
def getTemporaryTalkMsg_server(stat, err, gid, uid):
    return {
        'stat':stat,
        'err':err,
        'gid':gid,
        'uid':uid
    }

# 广播结束：19——>8019（server）
def geBoardcastHangUpMsg_server(stat, err, gid, uid):
    return {
        'stat':stat,
        'err':err,
        'gid':gid,
        'uid':uid
    }

# 广播：17——>8017（server）
def getBoardcastMsg_sever(stat, err, gid, uid):
    return {
        'stat': stat,
        'err': err,
        'gid': gid,
        'uid':uid
    }

# 呼叫结束：12——>8012（server）
def getVideoCallHangUpMsg_server(stat, err, ch, cid, sid, gid):
    return {
        'stat':stat,
        'err':err,
        'ch':ch,
        'cid':cid,
        'sid':sid,
        'gid':gid
    }

class udpSocket:
    def __init__(self, serverIP, serverPort, rtpData):
        self.serverIP = serverIP
        self.serverPort = serverPort
        self.rtpData = rtpData
        #self.localIP = socket.gethostbyname(socket.gethostname())              #部分服务器有多个网口，该方法不一定适用
        self.localIP = "114.44.176.184"
        self.localPort = 54321
        self.udpClient = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)       #创建UDP套接字
        self.udpClient.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)	#设置重用套接字地址
        self.udpClient.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1)      #设置UDP允许广播
        self.udpClient.setblocking(0)					        #将UDP套接字设置成非阻塞状态
        self.udpClient.settimeout(10)					        #设置超时时间为0.8s
        #self.udpClient.bind((self.localIP, self.localPort))                    #IP、Port绑定，若是要同时开启线程发送数据，不能绑定端口

    def send(self):
        log.info("Rtp sendData:"+repr(self.rtpData))
        data = self.rtpData
        data1 = "" #初始化
        data2 = "" #初始化
        while data:
            data1 = data[0:2]                                                   #分割字符串，获取前两个字符
            s = int(data1, 16)                                                  #字符串转换成16进制
            data2 += struct.pack('B', s)                                        #转换成字节流，“B“为格式符，代表一个unsigned char （具体请查阅struct）
            data = data[2:]                                                     #分割字符串，去掉字符串前两个字符
        self.udpClient.sendto(data2, (self.serverIP, self.serverPort))

        try:
            data, addr = self.udpClient.recvfrom(1024)
            log.info("Rtp recvData:"+repr(data))
        except Exception, e:
            log.error(str(e))

    def update(self,serverIP, serverPort, rtpData):
        self.serverIP = serverIP
        self.serverPort = serverPort
        self.rtpData = rtpData


